<template>
    <div>
        <el-card class="box-card" style="margin-top: 10px;">
            <div>
                <el-input
                    size="small"
                    placeholder="请输入司机姓名"
                    style="width: 200px;"
                    prefix-icon="el-icon-search"
                    v-model="name">
                </el-input>
                <el-select v-model="type" placeholder="请选择证件类型" size="small" style="margin-left: 10px;">
                  <el-option label="A1" value="A1" />
                  <el-option label="A2" value="A2" />
                  <el-option label="A3" value="A3" />
                  <el-option label="B1" value="B1" />
                  <el-option label="B2" value="B2" />
                  <el-option label="B3" value="B3" />
                  <el-option label="C1" value="C1" />
                  <el-option label="C2" value="C2" />
                  <el-option label="C3" value="C3" />
                </el-select>
                <el-button type="primary" icon="el-icon-search" style="margin-left: 10px;" size="small" @click="load()">搜索</el-button>
                <el-button type="info" icon="el-icon-refresh" size="small" @click="reset()">重置</el-button>
            </div>
            <div style="margin-top: 10px;">
                <el-dialog
                  :title="form.name + '司机的信息'"
                  :visible.sync="dialogVisible"
                  width="70%"
                  :before-close="handleClose">
                  <el-descriptions title="司机的基础信息" direction="vertical" :column="5" border>
                    <el-descriptions-item label="司机姓名">{{ form.name }}</el-descriptions-item>
                    <el-descriptions-item label="性别">{{ form.sex == 0 ? '男' : '女' }}</el-descriptions-item>
                    <el-descriptions-item label="年龄">{{ form.age }}</el-descriptions-item>
                    <el-descriptions-item label="邮箱">{{ form.email }}</el-descriptions-item>
                    <el-descriptions-item label="身份证号">{{ form.idNumber }}</el-descriptions-item>
                    <el-descriptions-item label="联系方式">{{ form.phone }}</el-descriptions-item>
                    <el-descriptions-item label="初次领取驾照时间">{{ form.firstTime }}</el-descriptions-item>
                    <el-descriptions-item label="驾驶证到期时间">{{ form.exp }}</el-descriptions-item>
                    <el-descriptions-item label="证件类型">{{ form.type }}</el-descriptions-item>
                    <el-descriptions-item label="驾龄是否三年">{{ form.isSatisfy }}</el-descriptions-item>
                  </el-descriptions>
                  <div class="title">司机照片信息</div>
                  <div style="margin-bottom: 10px;margin-top: 10px;">
                      <div class="pic-box">
                          <span>身份证正面照片</span>
                          <el-image
                                class="imgStyle"
                                :src="form.imgUrl1"
                                :preview-src-list="[form.imgUrl1]">
                          </el-image>
                      </div>
                      <div class="pic-box">
                          <span>司机免冠照片</span>
                          <el-image
                                class="imgStyle"
                                :src="form.imgUrl2"
                                :preview-src-list="[form.imgUrl2]">
                          </el-image>
                      </div>
                      <div class="pic-box">
                          <span>驾驶证主页照片</span>
                          <el-image
                                class="imgStyle"
                                :src="form.imgUrl3"
                                :preview-src-list="[form.imgUrl3]">
                          </el-image>
                      </div>
                      <div class="pic-box">
                          <span>人车合照</span>
                          <el-image
                                class="imgStyle"
                                :src="form.imgUrl4"
                                :preview-src-list="[form.imgUrl4]">
                          </el-image>
                      </div>
                      <div class="pic-box">
                          <span>交强险照片</span>
                          <el-image
                                class="imgStyle"
                                :src="form.imgUrl5"
                                :preview-src-list="[form.imgUrl5]">
                          </el-image>
                      </div>  
                  </div>
                  <el-descriptions title="司机下绑定的车辆" direction="vertical" :column="5" border>
                    <template v-for="(item,index) in form.carList">
                        <el-descriptions-item label="车牌号" :key="index">{{ item.number }}</el-descriptions-item>
                        <el-descriptions-item label="所属人" :key="index">{{ item.people }}</el-descriptions-item>
                        <el-descriptions-item label="车型" :key="index">{{ item.type }}</el-descriptions-item>
                        <el-descriptions-item label="车辆注册日期" :key="index">{{ item.creationTime }}</el-descriptions-item>
                        <el-descriptions-item label="车辆状态" :key="index">
                            <span v-show="item.status == 0">空闲</span>
                            <span v-show="item.status == 1">使用中</span>
                            <span v-show="item.status == 2">待年审</span>
                            <span v-show="item.status == 3">待修理</span>
                        </el-descriptions-item>
                    </template>
                  </el-descriptions>
                  <span slot="footer" class="dialog-footer">
                    <el-button @click="dialogVisible = false">取 消</el-button>
                    <el-button type="primary" @click="dialogVisible = false">确 定</el-button>
                  </span>
                </el-dialog>
                <el-dialog
                  title="修改司机信息"
                  :visible.sync="dialogVisible2"
                  width="70%"
                  :before-close="handleClose2">
                  <el-collapse>
                    <el-collapse-item title="个人信息" name="1">
                      <el-form ref="form" :model="form" label-width="150px" :inline="true">
                          <el-form-item label="司机姓名">
                            <el-input v-model="form.name"/>
                          </el-form-item>
                          <el-form-item label="性别" :inline="false">
                            <el-select v-model="form.sex" placeholder="请选择性别">
                              <el-option label="男" value="0" />
                              <el-option label="女" value="1" />
                            </el-select>
                          </el-form-item>
                          <el-form-item label="年龄">
                            <el-input v-model="form.age"/>
                          </el-form-item>
                          <el-form-item label="邮箱">
                            <el-input v-model="form.email"/>
                          </el-form-item>
                          <el-form-item label="身份证号">
                            <el-input v-model="form.idNumber"/>
                          </el-form-item>
                          <el-form-item label="联系方式">
                            <el-input v-model="form.phone"/>
                          </el-form-item>
                          <el-form-item label="初次领驾照日期">
                            <el-date-picker
                              v-model="form.firstTime"
                              type="date"
                              value-format="yyyy-MM-dd"
                              placeholder="选择日期"
                            />
                          </el-form-item>
                          <el-form-item label="驾驶证到期时间">
                            <el-date-picker
                              v-model="form.exp"
                              type="date"
                              value-format="yyyy-MM-dd"
                              placeholder="选择日期"
                            />
                          </el-form-item>
                          <el-form-item label="证件类型">
                            <el-select v-model="form.type" placeholder="证件类型">
                              <el-option label="A1" value="A1" />
                              <el-option label="A2" value="A2" />
                              <el-option label="A3" value="A3" />
                              <el-option label="B1" value="B1" />
                              <el-option label="B2" value="B2" />
                              <el-option label="B3" value="B3" />
                              <el-option label="C1" value="C1" />
                              <el-option label="C2" value="C2" />
                              <el-option label="C3" value="C3" />
                            </el-select>
                          </el-form-item>
                          <el-form-item label="驾龄是否三年">
                              <el-radio-group v-model="form.isSatisfy">
                                <el-radio label="是"></el-radio>
                                <el-radio label="否"></el-radio>
                              </el-radio-group>
                          </el-form-item>
                      </el-form>
                    </el-collapse-item>
                    <el-collapse-item title="车辆信息" name="2">
                        <el-popover
                          placement="right"
                          width="400"
                          v-model="visible">
                          <el-select v-model="value" placeholder="请选择" size="small">
                              <el-option
                                v-for="item in options"
                                :key="item.id"
                                :label="item.number"
                                :value="item.id">
                              </el-option>
                            </el-select>
                            <el-button type="primary" style="margin-left: 10px;" size="small" @click="handler()">确认分配</el-button>
                          <el-button slot="reference" type="success" style="float: right; padding: 5px; margin-bottom:10px !important;" icon="el-icon-circle-plus-outline" @click="getCarList()">
                              分配车辆
                          </el-button>
                        </el-popover>
                      <el-table
                          :data="form.carList"
                          border
                          style="width: 100%">
                          <el-table-column
                            prop="number"
                            label="车牌号">
                          </el-table-column>
                          <el-table-column
                            prop="age"
                            label="车龄">
                          </el-table-column>
                          <el-table-column
                            prop="carLength"
                            label="车长">
                          </el-table-column>
                          <el-table-column
                            prop="load"
                            label="载重">
                          </el-table-column>
                          <el-table-column
                            prop="type"
                            label="车型">
                          </el-table-column>
                          <el-table-column
                            prop="people"
                            label="车辆所有人">
                          </el-table-column>
                          <el-table-column
                            prop="creationTime"
                            label="车辆注册时间">
                          </el-table-column>
                          <el-table-column label="操作" align="center">
                              <template slot-scope="scope">
                                  <el-col :span="24">
                                    <el-button type="danger" icon="el-icon-delete" @click="cancel(scope.$index)">
                                        取消关联
                                    </el-button>
                                  </el-col>
                              </template>
                          </el-table-column>
                        </el-table>
                    </el-collapse-item>
                    <el-collapse-item title="照片信息" name="3">
                      <div class="pic-box">
                          <span>身份证正面照片</span>
                          <el-upload
                            class="avatar-uploader"
                            action="#"
                            :show-file-list="false"
                            :http-request="requestUpload"
                            :before-upload="beforeAvatarUpload1">
                            <img v-if="form.imgUrl1" :src="form.imgUrl1" class="avatar">
                            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                          </el-upload>
                      </div>
                      <div class="pic-box">
                          <span>司机免冠照片</span>
                          <el-upload
                            class="avatar-uploader"
                            action="#"
                            :show-file-list="false"
                            :http-request="requestUpload"
                            :before-upload="beforeAvatarUpload2">
                            <img v-if="form.imgUrl2" :src="form.imgUrl2" class="avatar">
                            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                          </el-upload>
                      </div>
                      <div class="pic-box">
                          <span>驾驶证主页照片</span>
                          <el-upload
                            class="avatar-uploader"
                            action="#"
                            :show-file-list="false"
                            :http-request="requestUpload"
                            :before-upload="beforeAvatarUpload3">
                            <img v-if="form.imgUrl3" :src="form.imgUrl3" class="avatar">
                            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                          </el-upload>
                      </div>
                      <div class="pic-box">
                          <span>人车合照</span>
                          <el-upload
                            class="avatar-uploader"
                            action="#"
                            :show-file-list="false"
                            :http-request="requestUpload"
                            :before-upload="beforeAvatarUpload4">
                            <img v-if="form.imgUrl4" :src="form.imgUrl4" class="avatar">
                            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                          </el-upload>
                      </div>
                      <div class="pic-box">
                          <span>交强险照片</span>
                          <el-upload
                            class="avatar-uploader"
                            action="#"
                            :show-file-list="false"
                            :http-request="requestUpload"
                            :before-upload="beforeAvatarUpload5">
                            <img v-if="form.imgUrl5" :src="form.imgUrl5" class="avatar">
                            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                          </el-upload>
                      </div> 
                    </el-collapse-item>
                  </el-collapse>
                  <span slot="footer" class="dialog-footer">
                    <el-button @click="dialogVisible2 = false">取 消</el-button>
                    <el-button type="primary" @click="save()">确 定</el-button>
                  </span>
                </el-dialog>
                <el-table
                    :row-style="{height: '0'}"
                    :cell-style="{padding: '5px'}"
                    :header-cell-style="{background:'#eef1f6',color:'#606266'}"
                    :data="tableData"
                    border
                    style="width: 100%">
                    <el-table-column
                      prop="name"
                      width="150"
                      label="姓名">
                    </el-table-column>
                    <el-table-column
                      width="100"
                      label="性别">
                      <template slot-scope="scope">
                          {{ scope.row.sex == 0 ? '男' : '女' }}
                      </template>
                    </el-table-column>
                    <el-table-column
                      width="100"
                      prop="age"
                      label="年龄">
                    </el-table-column>
                    <el-table-column
                      width="220"
                      prop="email"
                      label="邮箱">
                    </el-table-column>
                    <el-table-column
                      width="220"
                      prop="idNumber"
                      label="身份证号">
                    </el-table-column>
                    <el-table-column
                      width="200"
                      prop="phone"
                      label="联系方式">
                    </el-table-column>
                    <el-table-column
                      prop="firstTime"
                      width="200"
                      label="初领驾照日期">
                    </el-table-column>
                    <el-table-column
                      width="100"
                      label="驾照状态">
                      <template slot-scope="scope">
                         <el-tag type="success" v-show="scope.row.status == 0">正常</el-tag>
                         <el-tag type="warning" v-show="scope.row.status == 1">即将到期</el-tag>
                         <el-tag type="danger" v-show="scope.row.status == 2">已到期</el-tag>
                      </template>
                    </el-table-column>
                    <el-table-column
                      width="100"
                      prop="type"
                      label="证件类型">
                    </el-table-column>
                    <el-table-column
                      width="200"
                      prop="name"
                      label="操作">
                      <template slot-scope="scope">
                          <el-button type="text" icon="el-icon-view" @click="show(scope.row)">查看</el-button>
                          <el-button type="text" icon="el-icon-edit" style="color: #E6A23C;" @click="update(scope.row)">修改</el-button>
                          <el-button type="text" icon="el-icon-delete" style="color: red;" @click="del(scope.row.id)">删除</el-button>
                      </template>
                    </el-table-column>
                  </el-table>
                  <el-pagination
                    style="margin-top: 10px;"
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    :current-page="current"
                    :page-sizes="[2, 5, 10, 20]"
                    :page-size="size"
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="total">
                  </el-pagination>
            </div>
        </el-card>
    </div>
</template>

<script>
    import axios from 'axios'
    import request from '../../utils/request.js'
    export default {
        methods: {
           requestUpload() {
           },
           handleSizeChange(val) {
                this.size = val;
                this.load();
            },
            handleCurrentChange(val) {
                this.current = val;
                this.load();
            },
            load() {
                request.get("/driver/getDriverByConditionAndPage?current=" + this.current + "&size=" + this.size +
                 "&name=" + this.name + "&type=" + this.type).then(res=>{
                    this.tableData = res.data.records;
                    this.total = res.data.total;                            
                })
            },
            getCarList() {
                request.get("/car/getAllCarWithCompany").then(res=>{
                    this.options = res.data;                      
                })
            },
            reset() {
                this.type = '';
                this.name = '';
                this.load();
            },
            del(id) {
               this.$confirm('此操作将永久删除该司机的所有信息, 是否继续?', '提示', {
                 confirmButtonText: '确定',
                 cancelButtonText: '取消',
                 type: 'warning'
               }).then(() => {
                   request.delete("/driver/deleteDriverById?id=" + id).then(res=>{
                     if (res.code === 200) {
                         this.$message({
                           type: 'success',
                           message: '删除成功!'
                         });
                          // 为了在删除最后一页的最后一条数据时能成功跳转回最后一页的上一页
                         const totalPage = Math.ceil((this.total- 1) / this.size); // 总页数
                         this.current = this.current > totalPage ? totalPage : this.current;
                         this.current = this.current < 1 ? 1 : this.current;
                         this.load();
                     }  
                   })
                   
               }).catch(() => {
                 this.$message({
                   type: 'info',
                   message: '已取消删除'
                 });          
               });   
            },
            save() {
              let driverForm = {
                  id:this.form.id,
                  name:this.form.name,
                  sex:this.form.sex,
                  age:this.form.age,
                  email:this.form.email,
                  idNumber:this.form.idNumber,
                  phone:this.form.phone,
                  firstTime:this.form.firstTime,
                  exp:this.form.exp,
                  type:this.form.type,
                  isSatisfy:this.form.isSatisfy
              }
              let imgForm = {
                  imgUrl1: this.form.imgUrl1,
                  imgUrl2: this.form.imgUrl2,
                  imgUrl3: this.form.imgUrl3,
                  imgUrl4: this.form.imgUrl4,
                  imgUrl5: this.form.imgUrl5
              };
              let formData = new FormData();
              formData.append("drivers", JSON.stringify(driverForm));
              
              formData.append("cars", JSON.stringify(this.form.carList));
              
              if (this.file1 === undefined && this.file2 === undefined 
              && this.file3 === undefined && this.file4 === undefined && this.file5 === undefined) {
                 axios({
                     url: "http://localhost:9090/driver/updateDriver",
                     method: "POST",
                     data: formData,
                     headers: {
                         "Content-Type": "multipart/form-data",
                     },
                 })
                 .then(res => {
                     if (res.data.code === 200) {
                         this.$message({
                           message: '司机信息修改成功',
                           type: 'success'
                         });
                         this.load();
                         this.dialogVisible2 = false;
                     } else {
                         this.$message.error('司机信息修改失败');
                     }
                 })
                 .catch((e) => {
                     console.log(e.response.data.error.message)
                 });
              } else {
                  formData.append("imgs", JSON.stringify(imgForm));
                  if (this.file1 !== undefined) {
                      formData.append("file[]", this.file1);
                  }
                  if (this.file2 !== undefined) {
                      formData.append("file[]", this.file2);
                  }
                  if (this.file3 !== undefined) {
                      formData.append("file[]", this.file3);
                  }
                  if (this.file4 !== undefined) {
                      formData.append("file[]", this.file4);
                  }
                  if (this.file5 !== undefined) {
                      formData.append("file[]", this.file5);
                  }
                  axios({
                      url: "http://localhost:9090/driver/updateDriverAll",
                      method: "POST",
                      data: formData,
                      headers: {
                          "Content-Type": "multipart/form-data",
                      },
                  })
                  .then(res => {
                      if (res.data.code === 200) {
                          this.$message({
                            message: '司机信息修改成功',
                            type: 'success'
                          });
                          this.load();
                          this.dialogVisible2 = false;
                      } else {
                          this.$message.error('司机信息修改失败');
                      }
                  })
                  .catch((e) => {
                      console.log(e.response.data.error.message)
                  });
              }
            },
            show(val) {
                this.dialogVisible = true;
                this.form = val;
            },
            update(val) {
                this.dialogVisible2 = true;
                this.form = val;
            },
            handler() {
                this.visible = false;
                for (let i = 0; i < this.options.length; i ++) {
                    if (this.options[i].id == this.value) {
                        let flag = true;
                        for (let j = 0; j < this.form.carList.length; j ++) {
                            if (this.form.carList[j].id == this.options[i].id)
                                flag = false;
                        }
                        if (flag)
                            this.form.carList.splice(0, 0, this.options[i]);
                        else {
                            this.$message.error("该车辆已经存在");
                        }
                    }
                }
                this.value = '';
            },
            handleClose() {
              this.$confirm('确认关闭？')
              .then(() => {
                  this.dialogVisible = false;
              })
            },
            handleClose2() {
              this.$confirm('确认关闭？')
              .then(() => {
                  this.dialogVisible2 = false;
              })
            },
            cancel(val) {
                if (this.form.name != this.form.carList[val].people) {
                    this.$confirm('您确定要取消该司机与该车辆的关联吗?', '提示', {
                      confirmButtonText: '确定',
                      cancelButtonText: '取消',
                      type: 'warning'
                    }).then(() => {
                        this.form.carList.splice(val, 1);
                        this.$message.success("取消关联成功")
                    }).catch(() => {
                      this.$message({
                        type: 'info',
                        message: '已取消删除'
                      });          
                    });  
                }
                else {
                    this.$message.error("该车辆是司机所有，不能取消关联");
                }
            },
            beforeAvatarUpload1(file) {
                if (file.type.indexOf("image/") === -1) {
                    this.modal.msgError("文件格式错误，请上传图片类型,如：JPG，PNG后缀的文件。")
                } else {
                    const reader = new FileReader()
                    reader.readAsDataURL(file)
                    reader.onload = () => {
                        this.form.imgUrl1 = reader.result
                    }
                    this.file1 = file
                }
            },
            beforeAvatarUpload2(file) {
                if (file.type.indexOf("image/") === -1) {
                    this.modal.msgError("文件格式错误，请上传图片类型,如：JPG，PNG后缀的文件。")
                } else {
                    const reader = new FileReader()
                    reader.readAsDataURL(file)
                    reader.onload = () => {
                        this.form.imgUrl2 = reader.result
                    }
                    this.file2 = file
                }
            },
            beforeAvatarUpload3(file) {
                if (file.type.indexOf("image/") === -1) {
                    this.modal.msgError("文件格式错误，请上传图片类型,如：JPG，PNG后缀的文件。")
                } else {
                    const reader = new FileReader()
                    reader.readAsDataURL(file)
                    reader.onload = () => {
                        this.form.imgUrl3 = reader.result
                    }
                    this.file3 = file
                }
            },
            beforeAvatarUpload4(file) {
                if (file.type.indexOf("image/") === -1) {
                    this.modal.msgError("文件格式错误，请上传图片类型,如：JPG，PNG后缀的文件。")
                } else {
                    const reader = new FileReader()
                    reader.readAsDataURL(file)
                    reader.onload = () => {
                        this.form.imgUrl4 = reader.result
                    }
                    this.file4 = file
                }
            },
            beforeAvatarUpload5(file) {
                if (file.type.indexOf("image/") === -1) {
                    this.modal.msgError("文件格式错误，请上传图片类型,如：JPG，PNG后缀的文件。")
                } else {
                    const reader = new FileReader()
                    reader.readAsDataURL(file)
                    reader.onload = () => {
                        this.form.imgUrl5 = reader.result
                    }
                    this.file5 = file
                }
            },
        },
        data() {
          return {
            tableData: [],
            current:1,
            size:10,
            total:0,
            name:'',
            type:'',
            title:'',
            dialogVisible: false,
            dialogVisible2: false,
            visible: false,
            file1:undefined,
            file2:undefined,
            file3:undefined,
            file4:undefined,
            file5:undefined,
            form: {
                
            },
            options: [],
            value: ''
          }
        },
        mounted() {
            this.load();
        }
      }
</script>

<style scoped>
    .imgStyle {
        width: 90px;
        height: 120px;
        display: block;
        margin-top: 5px;
    }
    .title {
        font-size: 16px;
        font-weight: 700;
        color: #303133;
        margin-top: 10px;
    }
    .pic-box {
        display: inline-block;
        margin-left: 30px;
    }
    .avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 178px;
      height: 178px;
      line-height: 178px;
      text-align: center;
    }
    .avatar {
      width: 178px;
      height: 178px;
      display: block;
    }
</style>
